package com.changgou.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/***
 * 监听数据库的变化
 * @author ZJ
 */
@CanalEventListener
public class BusinessListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /***
     *
     * @param eventType 当前操作数据库的类型 INSERT DELETE UPDATE QUERY...
     * @param rowData 当前操作数据库的数据
     */
    @ListenPoint(schema = "changgou_business", table = {"tb_ad"})
    public void adUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        System.err.println("广告数据发生变化");
        System.out.println("eventType:" + eventType);

       /* //获取修改前数据
        for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
            if (column.getName().equals("position")) {
                System.out.println("发送消息到mq  ad_update_queue:" + column.getValue());
                rabbitTemplate.convertAndSend("", "ad_update_queue", column.getValue());  //发送消息到mq
                break;
            }
        }

        //获取修改后数据
        for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
            if (column.getName().equals("position")) {
                System.out.println("发送消息到mq  ad_update_queue:" + column.getValue());
                rabbitTemplate.convertAndSend("", "ad_update_queue", column.getValue());  //发送消息到mq
                break;
            }
        }*/

       /* rowData.getBeforeColumnsList().forEach((c) -> System.out.println("改变前的数据：" + c.getName() + "::" + c.getValue()));
        System.out.println("========================================");
        rowData.getAfterColumnsList().forEach((c) -> System.out.println("改变后的数据：" + c.getName() + "::" + c.getValue()));*/


        //发送位置信息到mq
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        for (CanalEntry.Column column : afterColumnsList) {
            if (column.getName().equals("position")) {
                //发的是列的值
                String value = column.getValue();
                //发消息
                rabbitTemplate.convertAndSend("", RabbitMQConfig.AD_UPDATE_QUEQU, value);
            }
        }
    }
}
